<template>
  <div class="order-management-container">
    <h2 class="page-title">订单管理</h2>
    
    <!-- 搜索和过滤 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="订单号">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable></el-input>
        </el-form-item>
        <el-form-item label="商家ID">
          <el-input v-model="queryParams.merchantId" placeholder="请输入商家ID" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
            <el-option label="待付款" :value="1"></el-option>
            <el-option label="已付款" :value="2"></el-option>
            <el-option label="配送中" :value="3"></el-option>
            <el-option label="已完成" :value="4"></el-option>
            <el-option label="已取消" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleDateRangeChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 订单列表 -->
    <el-card class="table-card">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部订单" name="all"></el-tab-pane>
        <el-tab-pane label="待付款" name="pending"></el-tab-pane>
        <el-tab-pane label="已付款" name="paid"></el-tab-pane>
        <el-tab-pane label="配送中" name="delivering"></el-tab-pane>
        <el-tab-pane label="已完成" name="completed"></el-tab-pane>
        <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
      </el-tabs>
      
      <el-table
        :data="orderList"
        border
        stripe
        v-loading="loading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
        <el-table-column prop="userId" label="用户ID" width="100"></el-table-column>
        <el-table-column prop="merchantId" label="商家ID" width="100"></el-table-column>
        <el-table-column prop="merchantName" label="商家名称" width="150"></el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="100">
          <template slot-scope="scope">
            ¥{{ scope.row.totalAmount ? scope.row.totalAmount.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="actualAmount" label="实付金额" width="100">
          <template slot-scope="scope">
            ¥{{ scope.row.actualAmount ? scope.row.actualAmount.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100">
          <template slot-scope="scope">
            {{ getPaymentMethodText(scope.row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getOrderStatusType(scope.row.status)">
              {{ getOrderStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderTime" label="下单时间" width="180"></el-table-column>
        <el-table-column prop="payTime" label="支付时间" width="180"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleViewDetail(scope.row)">查看</el-button>
            <el-button v-if="scope.row.status === 2" type="text" size="small" @click="handleDelivery(scope.row)">配送</el-button>
            <el-button v-if="scope.row.status === 1" type="text" size="small" class="danger-btn" @click="handleCancel(scope.row)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          :current-page="queryParams.page"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      :visible.sync="orderDetailVisible"
      width="800px">
      <div v-if="currentOrder" class="order-detail">
        <!-- 订单基本信息 -->
        <div class="detail-section">
          <div class="section-title">基本信息</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单ID">{{ currentOrder.id }}</el-descriptions-item>
            <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
            <el-descriptions-item label="用户ID">{{ currentOrder.userId }}</el-descriptions-item>
            <el-descriptions-item label="商家ID">{{ currentOrder.merchantId }}</el-descriptions-item>
            <el-descriptions-item label="商家名称">{{ currentOrder.merchantName }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getOrderStatusType(currentOrder.status)">
                {{ getOrderStatusText(currentOrder.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ currentOrder.orderTime }}</el-descriptions-item>
            <el-descriptions-item label="支付时间">{{ currentOrder.payTime || '未支付' }}</el-descriptions-item>
            <el-descriptions-item label="配送时间">{{ currentOrder.deliveryTime || '未配送' }}</el-descriptions-item>
            <el-descriptions-item label="完成时间">{{ currentOrder.completeTime || '未完成' }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <!-- 金额信息 -->
        <div class="detail-section">
          <div class="section-title">金额信息</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="商品总额">¥{{ currentOrder.totalAmount ? currentOrder.totalAmount.toFixed(2) : '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="配送费">¥{{ currentOrder.deliveryFee ? currentOrder.deliveryFee.toFixed(2) : '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="优惠金额">¥{{ currentOrder.discountAmount ? currentOrder.discountAmount.toFixed(2) : '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="实付金额">¥{{ currentOrder.actualAmount ? currentOrder.actualAmount.toFixed(2) : '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="支付方式">{{ getPaymentMethodText(currentOrder.paymentMethod) }}</el-descriptions-item>
            <el-descriptions-item label="支付状态">
              <el-tag :type="currentOrder.payStatus ? 'success' : 'danger'">
                {{ currentOrder.payStatus ? '已支付' : '未支付' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        
        <!-- 收货信息 -->
        <div class="detail-section">
          <div class="section-title">收货信息</div>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="收货人">{{ currentOrder.receiver }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ currentOrder.phone }}</el-descriptions-item>
            <el-descriptions-item label="收货地址">{{ currentOrder.address }}</el-descriptions-item>
            <el-descriptions-item label="订单备注">{{ currentOrder.remark || '无' }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <!-- 商品列表 -->
        <div class="detail-section">
          <div class="section-title">商品列表</div>
          <el-table
            :data="currentOrder.items || []"
            border
            stripe>
            <el-table-column prop="foodId" label="商品ID" width="80"></el-table-column>
            <el-table-column prop="foodName" label="商品名称" width="200"></el-table-column>
            <el-table-column prop="price" label="单价" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.price ? scope.row.price.toFixed(2) : '0.00' }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
            <el-table-column prop="subtotal" label="小计" width="100">
              <template slot-scope="scope">
                ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
          </el-table>
        </div>
        
        <!-- 订单日志 -->
        <div class="detail-section">
          <div class="section-title">订单日志</div>
          <el-timeline>
            <el-timeline-item
              v-for="(log, index) in currentOrder.logs"
              :key="index"
              :timestamp="log.time"
              :type="getLogType(log.action)">
              {{ log.content }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
    
    <!-- 配送对话框 -->
    <el-dialog
      title="订单配送"
      :visible.sync="deliveryDialogVisible"
      width="500px">
      <el-form :model="deliveryForm" ref="deliveryForm" label-width="100px">
        <el-form-item label="配送人员" prop="deliveryPerson" :rules="[{ required: true, message: '请输入配送人员姓名', trigger: 'blur' }]">
          <el-input v-model="deliveryForm.deliveryPerson" placeholder="请输入配送人员姓名"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="deliveryPhone" :rules="[{ required: true, message: '请输入联系电话', trigger: 'blur' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }]">
          <el-input v-model="deliveryForm.deliveryPhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="预计送达时间" prop="estimatedDeliveryTime" :rules="[{ required: true, message: '请选择预计送达时间', trigger: 'change' }]">
          <el-date-picker
            v-model="deliveryForm.estimatedDeliveryTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="deliveryForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deliveryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDelivery">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 取消订单对话框 -->
    <el-dialog
      title="取消订单"
      :visible.sync="cancelDialogVisible"
      width="500px">
      <el-form :model="cancelForm" ref="cancelForm" label-width="100px">
        <el-form-item label="取消原因" prop="reason" :rules="[{ required: true, message: '请选择取消原因', trigger: 'change' }]">
          <el-select v-model="cancelForm.reason" placeholder="请选择取消原因">
            <el-option label="用户申请取消" value="用户申请取消"></el-option>
            <el-option label="商家无法接单" value="商家无法接单"></el-option>
            <el-option label="商品缺货" value="商品缺货"></el-option>
            <el-option label="系统原因" value="系统原因"></el-option>
            <el-option label="其他原因" value="其他原因"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="cancelForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCancel">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { getOrder, getOrderByNo, cancelOrder } from '@/api/order'

export default {
  name: 'OrderManagement',
  data() {
    return {
      // 当前激活的标签页
      activeTab: 'all',
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        orderNo: '',
        userId: '',
        merchantId: '',
        status: '',
        startTime: '',
        endTime: ''
      },
      // 日期范围
      dateRange: [],
      // 订单列表
      orderList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 当前查看的订单
      currentOrder: null,
      // 订单详情对话框可见性
      orderDetailVisible: false,
      // 配送对话框可见性
      deliveryDialogVisible: false,
      // 配送表单
      deliveryForm: {
        orderId: null,
        deliveryPerson: '',
        deliveryPhone: '',
        estimatedDeliveryTime: '',
        remark: ''
      },
      // 取消订单对话框可见性
      cancelDialogVisible: false,
      // 取消订单表单
      cancelForm: {
        orderId: null,
        reason: '',
        remark: ''
      }
    }
  },
  created() {
    this.fetchOrderList()
  },
  methods: {
    // 获取订单列表
    fetchOrderList() {
      this.loading = true
      
      // 构建查询参数
      const params = {
        page: this.queryParams.page,
        size: this.queryParams.size
      }
      
      if (this.queryParams.orderNo) {
        params.orderNo = this.queryParams.orderNo
      }
      
      if (this.queryParams.userId) {
        params.userId = this.queryParams.userId
      }
      
      if (this.queryParams.merchantId) {
        params.merchantId = this.queryParams.merchantId
      }
      
      if (this.queryParams.status !== '') {
        params.status = this.queryParams.status
      }
      
      if (this.queryParams.startTime) {
        params.startTime = this.queryParams.startTime
      }
      
      if (this.queryParams.endTime) {
        params.endTime = this.queryParams.endTime
      }
      
      // 根据API文档 6.15 获取所有订单列表
      axios.get('/api/orders/admin', { params })
        .then(response => {
          if (response.code === 200) {
            this.orderList = response.data
            this.total = response.total
          } else {
            this.$message.error(response.message || '获取订单列表失败')
          }
        })
        .catch(error => {
          console.error('获取订单列表失败', error)
          this.$message.error('获取订单列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 处理日期范围变化
    handleDateRangeChange(val) {
      if (val) {
        this.queryParams.startTime = val[0]
        this.queryParams.endTime = val[1]
      } else {
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }
    },
    
    // 处理标签页点击
    handleTabClick(tab) {
      switch (tab.name) {
        case 'all':
          this.queryParams.status = ''
          break
        case 'pending':
          this.queryParams.status = 1
          break
        case 'paid':
          this.queryParams.status = 2
          break
        case 'delivering':
          this.queryParams.status = 3
          break
        case 'completed':
          this.queryParams.status = 4
          break
        case 'cancelled':
          this.queryParams.status = 5
          break
      }
      this.fetchOrderList()
    },
    
    // 处理查询
    handleQuery() {
      this.queryParams.page = 1
      this.fetchOrderList()
    },
    
    // 重置查询
    resetQuery() {
      this.dateRange = []
      this.queryParams = {
        page: 1,
        size: 10,
        orderNo: '',
        userId: '',
        merchantId: '',
        status: this.queryParams.status, // 保持当前标签页的状态筛选
        startTime: '',
        endTime: ''
      }
      this.fetchOrderList()
    },
    
    // 查看订单详情
    handleViewDetail(row) {
      // 根据API文档 6.2 根据ID获取订单信息
      getOrder(row.id)
        .then(response => {
          if (response.code === 200) {
            this.currentOrder = response.data
            
            // 根据API文档 7.1 根据订单ID获取订单详情
            axios.get(`/api/order-details/order/${row.id}`)
              .then(detailResponse => {
                if (detailResponse.code === 200) {
                  this.currentOrder.items = detailResponse.data
                  this.orderDetailVisible = true
                } else {
                  this.$message.error(detailResponse.message || '获取订单详情失败')
                }
              })
              .catch(error => {
                console.error('获取订单详情失败', error)
                this.$message.error('获取订单详情失败')
              })
          } else {
            this.$message.error(response.message || '获取订单信息失败')
          }
        })
        .catch(error => {
          console.error('获取订单信息失败', error)
          this.$message.error('获取订单信息失败')
        })
    },
    
    // 处理配送
    handleDelivery(row) {
      this.deliveryForm = {
        orderId: row.id,
        deliveryPerson: '',
        deliveryPhone: '',
        estimatedDeliveryTime: '',
        remark: ''
      }
      this.deliveryDialogVisible = true
    },
    
    // 提交配送
    submitDelivery() {
      this.$refs.deliveryForm.validate(valid => {
        if (valid) {
          // 根据API文档 6.9 开始配送接口
          axios.post(`/api/orders/${this.deliveryForm.orderId}/deliver`, {
            merchantId: this.$store.state.user.id // 管理员也使用该接口
          })
            .then(response => {
              if (response.code === 200) {
                this.$message.success('订单已开始配送')
                this.deliveryDialogVisible = false
                this.fetchOrderList()
              } else {
                this.$message.error(response.message || '配送操作失败')
              }
            })
            .catch(error => {
              console.error('配送操作失败', error)
              this.$message.error('配送操作失败')
            })
        } else {
          return false
        }
      })
    },
    
    // 处理取消订单
    handleCancel(row) {
      this.cancelForm = {
        orderId: row.id,
        reason: '',
        remark: ''
      }
      this.cancelDialogVisible = true
    },
    
    // 提交取消
    submitCancel() {
      this.$refs.cancelForm.validate(valid => {
        if (valid) {
          // 根据API文档 6.11 取消订单接口
          cancelOrder(
            this.cancelForm.orderId, 
            this.cancelForm.reason + (this.cancelForm.remark ? `: ${this.cancelForm.remark}` : ''), 
            this.$store.state.user.id
          )
            .then(response => {
              if (response.code === 200) {
                this.$message.success('订单已取消')
                this.cancelDialogVisible = false
                this.fetchOrderList()
              } else {
                  this.$message.error(response.message || '取消订单失败')
              }
            })
            .catch(error => {
              console.error('取消订单失败', error)
              this.$message.error('取消订单失败')
            })
        } else {
          return false
        }
      })
    },
    
    // 处理每页大小变化
    handleSizeChange(size) {
      this.queryParams.size = size
      this.fetchOrderList()
    },
    
    // 处理页码变化
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.fetchOrderList()
    },
    
    // 获取订单状态类型（用于标签颜色）
    getOrderStatusType(status) {
      const types = {
        1: 'warning',  // 待付款
        2: 'info',     // 已付款/已确认
        3: 'primary',  // 配送中
        4: 'success',  // 已完成
        5: 'danger'    // 已取消
      }
      return types[status] || 'info'
    },
    
    // 获取订单状态文本
    getOrderStatusText(status) {
      const texts = {
        1: '待付款',
        2: '已付款',
        3: '配送中',
        4: '已完成',
        5: '已取消'
      }
      return texts[status] || '未知状态'
    },
    
    // 获取支付方式文本
    getPaymentMethodText(method) {
      const texts = {
        1: '微信支付',
        2: '支付宝',
        3: '校园卡'
      }
      return texts[method] || '未知方式'
    },
    
    // 获取日志类型（用于时间线图标颜色）
    getLogType(action) {
      const types = {
        create: 'primary',
        pay: 'success',
        delivery: 'warning',
        complete: 'success',
        cancel: 'danger'
      }
      return types[action] || 'info'
    }
  }
}
</script>

<style scoped>
.order-management-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.danger-btn {
  color: #F56C6C;
}

.detail-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}
</style>